import React, { useState, useEffect } from 'react';
import { Link, withRouter } from 'react-router-dom';
import { List, ListView, NavBar, Icon, Toast, Result } from 'antd-mobile';
import { R, ORDER_STATUSES } from "@/assets/js/dict"
import { listMsgOfTutor } from "@/api/msg/msg.js";
import nodata from "@/assets/svg/nodata.svg"

import  "./msgOfTutor.scss"

const Item = List.Item;
const Brief = Item.Brief;
const myImg = (src, key) => <img src={src} key={key} className="spe am-icon am-icon-md" alt="" />;

/**
 * 家教的消息列表
 * @param props
 * @returns {*}
 * @constructor
 */
function MessagesOfParent (props) {

    let [userInfo] = useState(() => {
        let userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
        return userInfo
    });

    let [dataSource, setDataSource] = useState(new ListView.DataSource({
        rowHasChanged: (row1, row2) => row1 !== row2,
    }));

    let [messages, setMessages] = useState([]);

    //后台返回的分页数据
    let [records, setRecords] = useState({});

    let [word, setWord] = useState("加载中...");
    let [isLoading, setisLoading] = useState(true);


    function getMessages (pageNum, pageSize = 7) {
        listMsgOfTutor({ receiver: userInfo.id, pageNum: pageNum, pageSize: pageSize }, (re) => {
            if (R.isSuccess(re)) {
                let data = R.getData(re);
                if (!!data.dataList && data.dataList.length > 0) {
                    setRecords(data);
                    messages.push(...data.dataList);
                    setMessages(messages);
                    let d = dataSource.cloneWithRows(messages);
                    setDataSource(d);
                    setisLoading(false);
                    if (data.pageIndex === data.totalPage) {
                        setWord("亲，没有更多了");
                    } else {
                        setWord("已加载");
                    }
                } else {
                    setWord("亲，没有更多了");
                }
            }
        })
    }


    useEffect(() => {
        getMessages(1);
    }, []);

    //加载数据
    let onEndReached = (event) => {
        console.log("onEndReached---> ", event);
        if (isLoading || records.pageIndex === records.totalPage) {
            setWord("亲，没有更多了");
        } else {
            setisLoading(true);
            setWord("加载中...");
            getMessages(records.pageIndex + 1);
        }
    };

    const separator = (sectionID, rowID) => (
        <div
            key={`${sectionID}-${rowID}`}
            style={{
                backgroundColor: '#F5F5F9',
                height: 8,
                borderTop: '1px solid #ECECED',
                borderBottom: '1px solid #ECECED',
            }}
        />
    );



    const readStatus = function (r) {
        if (r.readed) {
            return (<span style={{ color: 'green' }}>已读</span>);
        } else {
            return (<span style={{ color: 'red' }}>未读</span>);
        }
    };

    function back () {
        props.history.push("/mainTutor")
    }

    const row = (rowData, sectionID, rowID) => {
        console.log("rowId->", rowID);
        return (
            <div key={rowID + rowData.id} style={{ padding: '0 15px' }}>
                <Item key={rowData.id}
                    arrow="horizontal"
                    multipleLine
                    wrap
                    extra={readStatus(rowData)}
                    onClick={() => {
                        sessionStorage.setItem("msg_id", rowData.id);
                        props.history.push({
                            pathname: "/messageDetailsOfParent", state: {
                                msg_id: rowData.id
                            }
                        });
                    }}
                    platform="cross"
                >
                    发送者：{rowData.source_display}
                    <Brief> 消息内容：{rowData.content}</Brief>
                    <Brief> 创建时间：{rowData.create_time}</Brief>
                </ Item>
            </div>
        );
    };

    if (messages.length === 0) {
        return (
            <div>
                <div className="page-title  home-tit">
                    <NavBar
                        mode="light"
                        icon={<Icon type="left" />}
                        leftContent={<span key={"return"}></span>}
                        onLeftClick={back}
                    >
                        消息列表
                </NavBar>
                </div>

                <div className="page-content  home-content">
                    <div className="publish-content-piece">
                        <div className="form-box">
                            <Result
                                buttonText={"返回主页"}
                                img={myImg(nodata, "none")}
                                title=""
                                message="暂无消息"
                                buttonType="primary"
                                onButtonClick={back}
                            />
                        </div>
                    </div>
                </div>
            </div>)
    } else {
        return (
            <div className="MessagesOfTutor">
                <div className="page-title  home-tit">
                    <NavBar
                        mode="light"
                        icon={<Icon type="left" />}
                        leftContent={<span key="bak"></span>}
                        onLeftClick={back}
                    >
                        消息列表
                </NavBar>
                </div>

                <div className="page-content  home-content">
                    <div className="publish-content-piece">
                        <ListView
                            dataSource={dataSource}
                            renderFooter={() => (<div style={{ padding: 30, textAlign: 'center' }}>
                                {word}
                            </div>)}
                            renderRow={row}
                            renderSeparator={separator}
                            className="am-list"
                            pageSize={4}
                            style={{
                                height: "calc(100vh - 42px)",
                                width:'100%',
                                overFlow: 'auto'
                            }}
                            onScroll={() => {
                                console.log('scroll');
                            }}
                            scrollRenderAheadDistance={800}
                            onEndReached={onEndReached}
                            onEndReachedThreshold={10}
                        />
                    </div>
                </div>
            </div>

        );
    }

}

export default withRouter(MessagesOfParent);